package io.renren.modules.personal.controller;

import io.renren.common.annotation.Login;
import io.renren.common.utils.R;
import io.renren.common.config.ConstantConfig;
import io.renren.modules.forYoung.service.ForYounyService;
import io.renren.modules.sys.dto.AttentionAndFansDto;
import io.renren.modules.sys.dto.LikeDto;
import io.renren.modules.sys.dto.LikeDto2;
import io.renren.modules.forYoung.entity.AttentionAndFans;
import io.renren.modules.forYoung.entity.ForYounyEntity;
import io.renren.modules.sys.entity.ImgEntiy;
import io.renren.modules.sys.entity.UserEntity;
import io.renren.modules.personal.service.PersonalService;
import io.renren.modules.sys.service.TokenService;
import io.renren.modules.sys.service.UserService;
import io.renren.common.utils.Jdpush;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 个人中心方向接口
 */
@RestController
@RequestMapping("/api/personal")
public class PersonalController {

    @Autowired
    PersonalService personalService;

    @Autowired
    TokenService tokenService;

    @Autowired
    ForYounyService forYounyService;

    @Autowired
    UserService userService;

    /**
     * 上传头像
     */
    @Login
    @PostMapping("upImg")
    @ApiOperation("上传头像")
    public R upImg(@RequestParam("params") List<MultipartFile> params,@ApiIgnore @RequestAttribute("userId") Long userId){
        /*int code=100;//保存成功
        String msg="";*/
        //File file= (File) params.get("params");
        System.out.println("");
        String returnUrl="";
        try {
            for(MultipartFile file:params){
                Map<String, Object> param = new HashMap<    String,Object>();
                String name=
                        file.getOriginalFilename();

                param.put("name", name);
                param.put("buffer",file.getBytes());
                Integer imgId= forYounyService.upload(param);
                System.out.println(imgId);
                returnUrl=returnUrl+"http://106.14.146.131:280/zte-api/api/young/getimage/"+imgId+";";
            }
        } catch (Exception e) {
            System.out.println(e);
        }

        UserEntity user = new UserEntity();
        user.setUserId(userId);
        user.setHeadImg(returnUrl);
        userService.updateHeadImageByUserId(user);

        return R.ok("头像上传成功",100).put("headImg",returnUrl);
    }



    /**
     * 获取user的所有信息，用户的关注数量，用户的粉丝数量
     */
    @Login
    @PostMapping("getUserAndCount")
    @ApiOperation("获取user的所有信息和用户的关注数量，用户的粉丝数量")
    public R getUserAndCount(@ApiIgnore @RequestAttribute("userId") Long userId,@RequestBody Map map) throws UnsupportedEncodingException {
        String token = (String) map.get("token");
        map.put("userId",userId);
        UserEntity user = personalService.getUserAndCount(map);
        if( null != user.getNickNameB()){
            user.setNickName(new String(user.getNickNameB(),"UTF-8"));
        }
        return R.ok("",100).put("data",user);
    }


    /**
     * 添加关注
     * params:userId 当前用户id
     *        attentionId 要关注的人的id
     */
    @Login
    @PostMapping("saveAttention")
    @ApiOperation("添加关注")
    public R saveAttention(@RequestBody Map map){
        //参数是传来的userId和fansId
        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId",userId);
       AttentionAndFans entity = personalService.getEntityByUserIdAndFansId(map);
        personalService.saveAttention(map);
       if(entity != null){
           personalService.updateHuxiangguanzhu(map);
       }



        Map<String, String> map2 = new HashMap<>();
        map2.put(ConstantConfig.PUSH_TAG, "MAINACTIVITY");

        Jdpush.sendAliasPush(ConstantConfig.APP_KEY, ConstantConfig.MASTER_SECRET,
                map.get("fansId")+"","@ 有人关注了你  快来点击查看吧 !~", map2);

        return R.ok("添加关注成功",100);

    }

    /**
     * 删除关注
     */
    @Login
    @PostMapping("delAttention")
    @ApiOperation("删除关注")
    public R delAttention(@RequestBody Map map){
        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId",userId);
        personalService.delAttention(map);
        personalService.updateHuxiangguanzhuToOne(map);
        return R.ok("删除关注成功",100);
    }



    /**
     * 获取我的粉丝列表 并判断两人之间的关系  1 2 3 状态
     */
    @Login
    @PostMapping("getMyFans")
    @ApiOperation("获取我的粉丝列表")
    public R getMyFans(@RequestBody Map map) throws UnsupportedEncodingException {
        Long userId = tokenService.getUserIdByToken((String) map.get("token"));
        map.put("userId",userId);

        List list = personalService.getMyFansList(map);

        if(list.size() == 0){
            return R.ok("您还没有粉丝",100).put("data",list);
        }
        for(int i = 0 ;i < list.size();i++){
            AttentionAndFansDto a = (AttentionAndFansDto)list.get(i);
            a.setNickName(new String(a.getNickNameB()));
        }
        return R.ok("查询成功",100).put("data",list);
    }


    /**
     * 获取我的关注列表
     */
    @Login
    @PostMapping("getMyAttentions")
    @ApiOperation("获取我的关注列表")
    public R getMyAttentions(@RequestBody Map map){
        Long userId = tokenService.getUserIdByToken((String) map.get("token"));
        map.put("userId",userId);

        List list = personalService.getMyAttentionList(map);
        if(list.size() == 0){
            return R.ok("您还没有关注的人",100).put("data",list);
        }

        for(int i = 0 ;i < list.size();i++){
            AttentionAndFansDto a = (AttentionAndFansDto)list.get(i);
            a.setNickName(new String(a.getNickNameB()));
        }
        return R.ok("查询成功",100).put("data",list);
    }


    /**
     * 编辑我的签名
     */
    @Login
    @PostMapping("updataMyIntroduction")
    @ApiOperation("编辑我的签名")
    public R updataMyIntroduction(@RequestBody Map map){
        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId",userId);

        int rows = personalService.updataMyIntroduction(map);
        if(rows != 0){
            return R.ok("修改成功",100);
        }
        return R.ok("网络故障请重试",100);
    }


    /**
     * 返回收藏课程的数量和我收藏的学习分享的数量
     */
    @Login
    @PostMapping("getMyCollectionCount")
    @ApiOperation("返回收藏课程的数量和我收藏的学习分享的数量")
    public R getMyCollectionCount(@RequestBody Map map){
        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId",userId);

       int myCourseCollectionCount = personalService.getMyCourseCollectionCount(map);
       int myForYoungCollectuinCount = personalService.getMyForYoungCollectuinCount(map);

       return R.ok("",100).put("myCourseCollectionCount",myCourseCollectionCount)
               .put("myForYoungCollectuinCount",myForYoungCollectuinCount);
    }


    /**
     * 获取我收藏的致青春中的学习分享的列表
     */
    @Login
    @PostMapping("getMyCollectionShareList")
    @ApiOperation("获取我收藏的致青春中的学习分享的列表")
    public R getMyCollectionShareList(@RequestBody Map map){
        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId",userId);

        List list = personalService.getMyCollectionShareList(map);
        if(list.size() != 0){
            return R.ok("查询成功",100).put("list",list);
        }
        return R.ok("主人您还没有收藏致青春中的学习分享呢~",100).put("list",list);
    }


    /**
     * 获取个人中心中我的消息  头像 昵称 时间 id 笔记的封面   谁赞了我的笔记
     */

    @Login
    @PostMapping("getMyLikeInfo")
    @ApiOperation("获取个人中心中谁赞了我的笔记")
    public R getMyLikeInfo(@RequestBody Map map){
        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId",userId);

     //首先要获取foryoung的封面

        List list = new ArrayList();
        //获取有点赞的foryoung的id
       List<Integer> idList =  personalService.getForYoungId(map);
       for (int i = 0; i < idList.size();i++){
           //LikeDto likeDto = new LikeDto();
           int id = idList.get(i);
           //获取封面集合的字符串
          String img=  personalService.getForYoungImgs(id);
           String[] imgList = img.split(";");
           String img1 = imgList[0]+";";
          //获取点赞的人的头像 昵称 user_id
           List<LikeDto2> likeDtoList = personalService.getLikeManInfo(map);
           for(int t = 0;t < likeDtoList.size();t++){
               LikeDto likeDto = new LikeDto();
               likeDto.setUserId(likeDtoList.get(t).getUserId());
               likeDto.setHeadImg(likeDtoList.get(t).getHeadImg());
               likeDto.setNickName(likeDtoList.get(t).getNickName());
               likeDto.setImage(img1);
               list.add(likeDto);
           }
       }
        return  R.ok("",100).put("list",list);
    }


    /**
     * 选择学校的接口
     */
    @Login
    @PostMapping("chooseSchool")
    @ApiOperation("选择学校的接口")
    public R chooseSchool(@RequestBody Map map){
        //int schoolName = (Integer) map.get("schoolName");
        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId",userId);
        if(map.get("schoolId") == null){
            return R.error(101,"学校不能为空");
        }
        String schoolName = personalService.getschoolNameById(map);
        map.put("schoolName",schoolName);
        personalService.updateSchoolById(map);

        return R.ok("选择学校成功",100);
    }

    /**
     * 全部查询学校 按照首字母的拼音
     */
    //@Login
    @GetMapping("selectSchool")
    @ApiOperation("全部查询学校")
    public R selectSchool(){
       List schoolList = personalService.selectSchool();

       if(schoolList.size() != 0){
           return R.ok("",100).put("list",schoolList);
       }else{
           return R.ok("程序员小哥哥还没有录入学校呢哦~",100).put("list",schoolList);
       }
    }

    /**
     * 模糊用户查询
     */
    @Login
    @PostMapping("getUsers")
    @ApiOperation("模糊用户查询")
    public R getUsers(@RequestBody Map map) throws UnsupportedEncodingException {
        if(map.get("nickName") == null){
            return R.error(101,"查询内容不能为空哦~");
        }
        String nickName = (String)map.get("nickName");
        byte[] name = nickName.getBytes();
       List list =  personalService.getUsers(name);

       if(list.size() != 0){
           return R.ok("查询成功",100).put("list",list);
       }
       return R.ok("查无此用户",100).put("list",list);
    }

    @PostMapping("getUserIsAttention")
    @ApiOperation("根据用户id查询两个用户是否存在关系")
    public R getUserIsAttention(@RequestBody Map<String,String> map){
        String userId = map.get("userId");
        String fansId = map.get("fansId");

        if (userId == null){
            return R.ok("userId不能为空",101);
        }

        if (fansId == null){
            return R.ok("fansId不能为空",102);
        }

        String attention = personalService.getIsAttention(map);
        if (attention==null){
            return R.ok("查不到此关系",100).put("isAttention",0);
        }else {
            return R.ok("查询成功",100).put("isAttention",attention);
        }



    }





    /**
     * 根据userId获取当前人的致青春
     */
    /*@Login
    @PostMapping("getForYoungByUserId")
    @ApiOperation("根据userId获取当前人的致青春")
    public R getForYoungByUserId(@RequestBody Map map){
        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId",userId);
        List list = personalService.getForYoungByUserId(userId);
        if(list.size() != 0){
            return R.ok("",100).put("list",list);
        }
        return R.ok("他(她)还没有发布致青春呢哦！",100).put("list",list);
    }*/

    /**
     * 根据userId获取当前人的致青春
     */
    @Login
    @PostMapping("getForYoungByUserId")
    @ApiOperation("根据userId获取当前人的致青春")
    public R getMyForYoung(@RequestBody Map map) throws UnsupportedEncodingException {
        Long userId = Long.valueOf(map.get("userId").toString());
        map.put("userId", userId);

        List<ForYounyEntity> list = forYounyService.getMyForYoung(map);
        if (list.size() == 0) {
            return R.ok("他(她)还没有发布您的致青春呢~", 100).put("list", list);
        }
        for (int s = 0; s < list.size(); s++) {
            ForYounyEntity forYounyEntity = (ForYounyEntity) list.get(s);
            try {
                if (forYounyEntity.getImgs() != null) {
                    String[] imgsList = forYounyEntity.getImgs().split(";");
                    String[] wh = forYounyEntity.getImgswh().split(";");
                    List<ImgEntiy> imgEntiys = new ArrayList<>();
                    for (int i = 0; i < imgsList.length; i++) {
                        ImgEntiy imgEntiy = new ImgEntiy();
                        String[] whh = wh[i].split(":");
                        imgEntiy.setImgUrl(imgsList[i]);
                        imgEntiy.setWidth(whh[0]);
                        imgEntiy.setHeigh(whh[1]);
                        imgEntiys.add(imgEntiy);
                    }
                    forYounyEntity.setImgList(imgEntiys);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return R.ok("查询成功~", 100).put("list", list);
    }


    /**
     * 获取user的所有信息和用户的关注数量，用户的粉丝数量 BY USERID
     * @param map
     * @return
     * @throws UnsupportedEncodingException
     */
    @Login
    @PostMapping("getUserAndCountById")
    @ApiOperation("获取user的所有信息和用户的关注数量，用户的粉丝数量")
    public R getUserAndCountById(@RequestBody Map map) throws UnsupportedEncodingException {
        Long userId = Long.valueOf(map.get("userId").toString());
        map.put("userId",userId);
        UserEntity user = personalService.getUserAndCount(map);

        if( null != user.getNickNameB()){
            user.setNickName(new String(user.getNickNameB(),"UTF-8"));
        }
        return R.ok("",100).put("data",user);
    }

    /**
     * 通过userId获取粉丝列表
     */
    @Login
    @PostMapping("getMyFansById")
    @ApiOperation("通过userId获取粉丝列表")
    public R getMyFansById(@RequestBody Map map) throws UnsupportedEncodingException {
        List list = personalService.getMyFansList(map);
        if(list.size() == 0){
            return R.ok("您还没有粉丝",100).put("data",list);
        }
        for(int  i = 0 ; i < list.size();i++){
            AttentionAndFansDto a = (AttentionAndFansDto)list.get(i);
            a.setNickName(new String(a.getNickNameB()));
        }
        return R.ok("查询成功",100).put("data",list);
    }

    /**
     * 获取他人的关注列表
     */
    @Login
    @PostMapping("getMyAttentionsById")
    @ApiOperation("获取他人的关注列表")
    public R getMyAttentionsById(@RequestBody Map map){
        List list = personalService.getMyAttentionList(map);
        if(list.size() == 0){
            return R.ok("您还没有关注的人",100).put("data",list);
        }
        for(int  i = 0 ; i < list.size();i++){
            AttentionAndFansDto a = (AttentionAndFansDto)list.get(i);
            a.setNickName(new String(a.getNickNameB()));
        }
        return R.ok("查询成功",100).put("data",list);
    }
}
